/*
 * Substring with Concatenation of All Words
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).
 */
package com.xinpan.exercise;

import java.util.ArrayList;
import java.util.HashMap;


public class SubStringWithConcantinationofAllWords {
    public ArrayList<Integer> findSubstring(String S, String[] L) {
        // Start typing your Java solution below
        // DO NOT write main() function
        HashMap<String, Integer> wSet = new HashMap<String, Integer>();
        HashMap<String, Integer> toFind = new HashMap<String, Integer>();
        int len = L[0].length();
        
        for(int i = 0; i < L.length; i++)
        {
            if(wSet.get(L[i]) == null)
                wSet.put(L[i], 1);
            else
                wSet.put(L[i], wSet.get(L[i])+1);
        }
          
        int clen = len * L.length;
        ArrayList<Integer> res = new ArrayList<Integer>();
        
        for(int i = 0; i <= S.length()-clen; i++)
        {
            toFind.clear();
            int j = 0;
            for(; j < L.length; j++)
            {
                int k = i+j*len;
                String str = S.substring(k, k+len);
                if(wSet.get(str) == null)
                    break;
                if(toFind.get(str) == null)
                    toFind.put(str, 1);
                else
                    toFind.put(str, toFind.get(str)+1);
                
                if(toFind.get(str) > wSet.get(str))
                    break;
            }
            if(j == L.length)
                res.add(i);
        }
        
        return res;
    }
    
    public static void main(String[] args)
    {
    	SubStringWithConcantinationofAllWords t = new SubStringWithConcantinationofAllWords();
    	String[] w = {"foo", "bar"};
    	t.findSubstring("barfoothefoobarman", w);
    }
}
